package com.raports.items;

import com.appclient.DaoInstanceEnum;
import com.appclient.ScreensFramework;
import static com.appclient.Start.stage;
import com.carpark.ejb.Model.ParkingpassesModel;
import com.google.common.io.Files;
import com.raports.RaportControlledScreen;
import com.raports.RaportScreensController;
import com.raports.RaportScreensFramework;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.GridPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRProperties;

import net.sf.jasperreports.engine.xml.JRXmlLoader;

/**
 *
 * @author Sawior
 */
public class ClientsRaportController implements Initializable, RaportControlledScreen {

    private RaportScreensController myController;
    @FXML
    private WebView web1;
    @FXML
    private WebView web2;
    @FXML
    private Button save;
    @FXML
    private TabPane tabPane;
    @FXML
    private Tab month;
    @FXML
    private Tab all;
    @FXML
    private ChoiceBox bestSelect;
    @FXML
    private GridPane dateGrid;
    @FXML
    private Button generate;
    @FXML
    private Label nRec;
    private WebEngine webEngine;
    private FileChooser fileChooser;
    private File file;
    private JasperPrint jasperPrint;

    private void loadRaport() {
        try {
            JRProperties.setProperty("net.sf.jasperreports.export.character.encoding", "ISO-8859-2");
            JRProperties.setProperty("net.sf.jasperreports.default.pdf.encoding", "ISO-8859-2");

            InputStream inputStream = new FileInputStream(".\\src\\main\\resources\\clientTypes.jrxml");
           
            Map parameters = new HashMap();

            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            Connection connection = connectToDatabase();
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);

            JasperExportManager.exportReportToHtmlFile(jasperPrint, ".\\src\\main\\resources\\clientTypes.html");
            File f = new File(".\\src\\main\\resources\\clientTypes.html");
            web1.getEngine().load(f.toURI().toURL().toString());
        } catch (JRException ex) {
            Logger.getLogger(PassesRaportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PassesRaportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PassesRaportController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void setScreenParent(RaportScreensController screenParent) {
        myController = screenParent;
        loadRaport();
    }

    public void initialize(URL url, ResourceBundle rb) {
        tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
            @Override
            public void changed(ObservableValue<? extends Tab> tab, Tab month, Tab all) {

                if (tabPane.getSelectionModel().isSelected(0)) {
                    generate.setVisible(false);
                    nRec.setVisible(false);
                    bestSelect.setVisible(false);
                }
                if (tabPane.getSelectionModel().isSelected(1)) {

                    generate.setVisible(true);
                    nRec.setVisible(true);
                    bestSelect.setVisible(true);
                }
            }
        });

        generate.setVisible(false);
        nRec.setVisible(false);
        bestSelect.setVisible(false);
        initializeComboBox();
        generateMonthReport();
    }

    @FXML
    private void handleButtonAction(ActionEvent event) throws JRException {
        if (event.getSource() == save) {
            createFileChooer();
            file = fileChooser.showSaveDialog(stage);
            if (file != null) {
                JasperExportManager.exportReportToPdfFile(jasperPrint, file.getAbsolutePath());
            }
        }
        if (event.getSource() == generate) {
            generateMonthReport();
        }
    }

    public void createFileChooer() {

        fileChooser = new FileChooser();

        //Set extension filter
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF (*.pdf)", "*.pdf");
        fileChooser.getExtensionFilters().add(extFilter);
    }

    public static Connection connectToDatabase() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost/car20park13", "root", "");
        } catch (Exception e) {
            String text = "Could not connect to the database: " + e.getMessage() + " "
                    + e.getLocalizedMessage();
            System.out.println(text);
        }
        return connection;
    }

    public void initializeComboBox() {
        bestSelect.getSelectionModel().select("10");

    }

    public void generateMonthReport() {
        int m = Integer.parseInt((String) bestSelect.getValue());

        try {
            JRProperties.setProperty("net.sf.jasperreports.export.character.encoding", "ISO-8859-2");
            JRProperties.setProperty("net.sf.jasperreports.default.pdf.encoding", "ISO-8859-2");

            InputStream inputStream = new FileInputStream(".\\src\\main\\resources\\activeCLients.jrxml");
            Map<String, Object> params = new HashMap();
            params.put("ogr", m);
            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            Connection connection = connectToDatabase();
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            jasperPrint = JasperFillManager.fillReport(jasperReport, params, connection);

            JasperExportManager.exportReportToHtmlFile(jasperPrint, ".\\src\\main\\resources\\activeCLients.html");

            File f = new File(".\\src\\main\\resources\\activeCLients.html");
            web2.getEngine().load(f.toURI().toURL().toString());
            params.clear();

        } catch (JRException ex) {
            Logger.getLogger(PassesRaportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PassesRaportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PassesRaportController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
